<?php
class Inbox extends TbAbstract
{
    protected $_table = 'Inbox';

    static protected $_instance = null;
	public function sendInboxAccount($id, $text){
		$db = Db::getInstance();
		$sql = sprintf("SELECT COUNT(*) as c1 FROM Account WHERE id='%s' LIMIT 1",
				$db->real_escape_string($id));
		$result = $db->query($sql);
		$arr = $result->fetch_assoc();
		if($arr['c1'] == 0){
			return false;
		}
		$sql = sprintf("INSERT INTO Inbox(text,accountId,open) VALUES('%s','%s',0)",
				$db->real_escape_string($text),
				$db->real_escape_string($id));
		if($db->query($sql)){
			return true;
		}
		else {
			Log::error($db->error);
			return false;
		}
	}
	
	public function sendInboxAll($text){
		$db = Db::getInstance();
		$db->autocommit(FALSE);
		$sql = "SELECT id FROM Account";
		$result = $db->query($sql);
		$values = array();
		while($arr = $result->fetch_assoc()){
			$values[] = sprintf("('%s','%s',0)",
					$db->real_escape_string($text),
					$db->real_escape_string($arr['id']));
		}
		$valueAll = implode(',', $values);
		$sql = "INSERT INTO Inbox(text,accountId,open) VALUES".$valueAll;
		if($db->query($sql)){
			$db->commit();
			return true;
		}
		else {
			Log::error($db->error);
			$db->rollback();
			return false;
		}
	}
	
	public function openMessage($id){
		$db = Db::getInstance();
		$sql = sprintf('UPDATE Inbox SET open=1', $db->real_escape_string($id));
		if($db->query($sql)){
			return true;
		}
		else{
			Log::error($db->error);
			return false;
		}
	}
}